# Function to make First Letter capital
capitalize = function(str){
  c = strsplit(str, " ")[[1]]
  out = paste(toupper(substring(c, 1,1)), substring(c, 2), sep="", collapse=" ")
  return(out)
  }


# Extract number of control/treated obs in model data
extract = function(model, return, tvar = "post"){
  t = table(model$model[, tvar])
  control_obs = as.integer(t["0"])
  treated_obs = as.integer(t["1"])
  if(return == "c"){
    return(control_obs)
  }else if(return == "t"){
    return(treated_obs)
  }else{stop("return what? 'c' or 't'")}
}


# custom ggplot theme
theme_nice = function() {
  theme_minimal(base_family = "Archivo Narrow") +
    theme(panel.grid.minor = element_blank(),
          plot.background = element_rect(fill = "white", color = NA),
          plot.title = element_text(face = "bold"),
          axis.title = element_text(face = "bold"),
          strip.text = element_text(face = "bold", size = rel(0.8), hjust = 0),
          strip.background = element_rect(fill = "grey80", color = NA),
          legend.title = element_text(face = "bold"))
}

# # My Stargazer
# my_stargazer = function(dest_file, model_list, omit, title, label, order,
#   covariate.labels, notes_table, dep.var.labels,
#   dep.var.labels.include = TRUE, se = NULL){
#
#   filecon = file(dest_file)
#   writeLines(
#     stargazer(model_list, omit = omit, title = title, label = label,
#       order = order, covariate.labels = covariate.labels, notes = notes_table,
#       omit.stat = c("f", "ser"),
#       intercept.bottom = FALSE,
#       column.sep.width = "-20pt",
#       multicolumn = FALSE,
#       dep.var.caption = "",
#       se = se,
#       dep.var.labels = dep.var.labels,
#       dep.var.labels.include = dep.var.labels.include,
#       font.size = "small",
#       digits = 3,
#       digits.extra = 0,
#       star.char = c("+", "*", "**", "***"),
#       star.cutoffs = c(0.1, 0.05, 0.01, 0.001),
#       notes.align = "c",
#       align = TRUE,
#       no.space = TRUE,
#       add.lines = add.lines,
#       notes.label = "",
#       notes.append = FALSE),
#   filecon)
#   close(filecon)
#
# }

# Read CIS stuff

readCIS = function(folder){

  files = list.files(folder)
  codefile = files[grepl("^ES\\d*$", files)]
  datafile = files[grepl("^DA\\d*$", files)]

  guide = readLines(paste0(folder, "/", codefile))
  # guide = gsub("^\\s+", "", guide)

  # Start and end for code guide
  str = which(grepl("^.ESTU", guide))[1]
  end = which(guide == "")[1]-1

  # Extract and split
  guide_s = guide[str:end]
  guide_s = unlist(str_split(guide_s, " "))
  guide_s = guide_s[guide_s != "."]
  # Create df with question and fixed width value
  guide_df = as.data.frame(matrix(guide_s, ncol = 2, byrow = TRUE))
  names(guide_df) = c("q", "fw_raw")
  # Extract first value of fixed width
  guide_df$fw_int = as.integer(gsub("(\\d*).*", "\\1", guide_df$fw_raw))
  # Checking
  if(any(is.na(guide_df$fw_int))){
    print(subset(guide_df, is.na(fw_int)))
    warning("Problem with some column width numbers!")
  }
  # Get final number (last 3)
  total_chr = as.integer(str_sub(guide_df$fw_raw[nrow(guide_df)], -3L, -1L))
  # Get number of columns
  guide_df$fw = c(diff(guide_df$fw_int),
    total_chr - guide_df$fw_int[nrow(guide_df)])

  # Change first value
  guide_df$q[1] = gsub("/EST", "EST", guide_df$q[1])

  # Read file
  data = read.fwf(paste0(folder, "/", datafile),
    widths = guide_df$fw, col.names = guide_df$q)

  # Assign CCAA names
  data$CCAA = recode(data$CCAA,
    '1' = 'andalucia',
    '2' = 'aragon',
    '3' = 'asturias',
    '4' = 'baleares',
    '5' = 'canarias',
    '6' = 'cantabria',
    '7' = 'castilla-la mancha',
    '8' = 'castilla y leon',
    '9' = 'catalunya',
    '10' = 'comunitat valenciana',
    '11' = 'extremadura',
    '12' = 'galicia',
    '13' = 'madrid',
    '14' = 'murcia',
    '15' = 'navarra',
    '16' = 'euskadi',
    '17' = 'la rioja',
    '18' = 'ceuta',
    '19' = 'melilla')

  # destfile = paste0("data/CIS", gsub("DA", "", datafile), ".csv")
  # write.csv(data, destfile, row.names = F)
  return(data)

}
